import os
from pathlib import Path

import sys
print(sys.platform)
if sys.platform == 'darwin':
    # mac 上有问题，加了下面两句。线上环境centos没有问题，可以把下面两句注释掉
    import pymysql
    pymysql.install_as_MySQLdb()


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-#o$=%3&j7f&feu6#of%6tu=04uo$npz!_!oz*z9_8p3fz!t!dd'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    # 'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    # 'django.contrib.sessions',
    # 'django.contrib.messages',
    'django.contrib.staticfiles',
    'ninja',
    'index',
]

MIDDLEWARE = [
    # 'django.middleware.security.SecurityMiddleware',
    # 'django.contrib.sessions.middleware.SessionMiddleware',
    # 'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    # 'django.contrib.auth.middleware.AuthenticationMiddleware',
    # 'django.contrib.messages.middleware.MessageMiddleware',
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'django_prometheus.middleware.PrometheusBeforeMiddleware',
    # 'django_prometheus.middleware.PrometheusAfterMiddleware',
    'mainsys.middleware.CheckMiddleware'
]


ROOT_URLCONF = 'mainsys.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/'), ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mainsys.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
    }
}

CACHE_ROOT = os.path.join(BASE_DIR, "mainsys", "cache")
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': CACHE_ROOT,
        'TIMEOUT': 3600 * 12,
        'OPTIONS': {
            'MAX_ENTRIES': 2000
        }
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

from django.utils.translation import gettext_lazy as _

LANGUAGES = [
    ('zh-Hans', _('Chinese')),
]

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / 'static',  # BASE_DIR 是项目根目录（需在 settings.py 开头定义）
]

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

##################
# 可在后台修改的一些设置 参见 config.example
##################

es_config = {}

mq_config = {}

api_log = {}

# nacos 环境配置
env_config_dict = {
    'dev': {
        'addresses': 'http://nacos-ops.xx.com:80',
        'username': 'saas-api',
        'password': '',
        'namespace': 'saas-api-dev',
        'data_id': 'saas-api-dev.yml',
        'group': 'saas-api-dev',
    },
    'test': {
        'addresses': 'http://nacos-ops.xx.com:80',
        'username': 'saas-api',
        'password': '',
        'namespace': 'saas-api-test',
        'data_id': 'saas-api-test.yml',
        'group': 'saas-api-test'
    },
    'pre': {
        'addresses': 'http://nacos-ops.xx.com:80',
        'username': 'saas-api',
        'password': '',
        'namespace': 'pre-pythonapi',
        'data_id': 'saas-api-pre.yml',
        'group': 'saas-api-pre'
    },
    'prod': {
        'addresses': 'http://nacos-ops.xx.com:80',
        'username': 'saas-api',
        'password': '',
        'namespace': 'pythonapi',
        'data_id': 'saas-api-prod.yml',
        'group': 'saas-api-prod'
    },
}

#
# # 从nacos下载配置
# def update_config():
#     import nacos
#
#     # 根据系统环境下载对应配置
#     app_env = os.getenv('APP_ENV', 'dev')
#     env_config = env_config_dict.get(app_env, {})
#     namespace = env_config.get('namespace')
#     data_id = env_config.get('data_id')
#     group = env_config.get('group')
#     addresses = env_config.get('addresses')
#     username = env_config.get('username')
#     password = env_config.get('password')
#
#     client = nacos.NacosClient(addresses, namespace=namespace, username=username, password=password)
#
#     app_config = client.get_config(data_id, group)
#
#     if app_config:
#         with open('mainsys/config.py', 'w') as f:
#             f.write(app_config)
#     else:
#         raise ValueError('%s 环境配置下载失败' % app_env)
#
#
# update_config()

try:
    from mainsys.config import *
except ImportError as e:
    if "config" not in str(e):
        raise e
